'use strict';

import React from 'react';
import {
  StyleSheet, Text, View, ListView, Image, TouchableHighlight,
  Dimensions, ActivityIndicator, RefreshControl, AlertIOS
} from 'react-native'

//第三方组件
import Icon from 'react-native-vector-icons/Ionicons'

//自定义组件
import Detail from './detail'
import Header from '../common/header'
import request from '../common/request'
import config from '../common/config'

let width = Dimensions.get('window').width  //获取屏幕的宽度

//缓存整个列表的数据
let cachedResults = {
  nextpage: 1,  //下一页
  items: [], //列表数据
  total: 0  //总记录条数
};

//数据列表中的项，组件封装
const Item = React.createClass({
  getInitialState() {
    let row = this.props.row; //取到属性中的值
    return {row: row, up: row.up}
  },

  //点赞（每点击时取反）
  _up(){
    let url = config.api.base + config.api.up;
    let up = !this.state.up;
    let body = {accessToken: 'abcd', id: this.state.row._id, up: up ? 'yes' : 'no'};

    request.post(url, body)
      .then((data) => {
        if (data.success) {
          this.setState({up: up});
        }
        else {
          AlertIOS.alert('点赞失败，稍后再试');
        }
      });
  },

  render(){
    let row = this.state.row;
    return (<TouchableHighlight onPress={this.props.onPress}>
        <View style={styles.item}>
          <Text style={styles.title}>{row.title}</Text>
          <Image source={{uri: row.thumb}} style={styles.thumb}>
            <Icon name='ios-play' size={28} style={styles.play}/>
          </Image>
          <View style={styles.itemFooter}>
            <View style={styles.handleBox}>
              <Icon name={this.state.up ? 'ios-heart' :'ios-heart-outline' }
                    size={28} onPress={this._up}
                    style={this.state.up ? styles.up : styles.down}/>
              <Text style={styles.handleText} onPress={this._up}>喜欢</Text>
            </View>
            <View style={styles.handleBox}>
              <Icon name='ios-chatboxes-outline' size={28} style={styles.comment}/>
              <Text style={styles.handleText}>评论</Text>
            </View>
          </View>
        </View>
      </TouchableHighlight>
    )
  }
})


const List = React.createClass({
  getInitialState() {
    let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    return {
      isRefreshing: false,  //是否正在下拉刷新，默认flase
      isLodingTail: false,  //是否正在获取数据，默认false
      dataSource: ds.cloneWithRows([])  //默认列表为空数据
    };
  },

  //装载列表数据项，row是dataSource中的一条数据对象
  _renderRow(row){
    return (<Item key={row._id} onPress={()=>this._loadDetail(row)} row={row}/>)
  },

  //进入视频详细页面
  _loadDetail(row){
    this.props.navigator.push({
      name: 'detail',
      component: Detail,
      params: {data: row}  //将数据项对象传递给详情页
    });
  },

  //一般情况下，会在该事件中进行页面初始化数据的异常请求
  componentDidMount(){
    this._fetchData(0);
  },

  //首次获取列表数据
  _fetchData(page){
    this.setState({isLodingTail: true, isRefreshing: true});  //打开标记，开始加载请求数据
    request.get(config.api.base + config.api.creations, {accessToken: 'abc88'})
      .then((data) => {
        console.log(data)
        if (data.success) {  //请求成功
          let items = cachedResults.items.slice(); //拿到现有已加载的数据
          items = (page === 0) ? data.data.concat(items) : items.concat(data.data);  //拼接新获取到的数据，page=0是下拉，向前拼接

          cachedResults.items = items;
          cachedResults.total = data.total;
          if (page === 0) {
            cachedResults.nextpage += 1;
          }

          this.setState({
            dataSource: this.state.dataSource.cloneWithRows(cachedResults.items)
          });
        }
        //不管请求成功与否，都要更新的状态
        this.setState({isLodingTail: false, isRefreshing: false}); //加载数据完成，关闭标记
      })
  },

  //是否有更多的列表数据
  _hasData(){
    return cachedResults.total !== cachedResults.items.length;
  },

  //获取更多数据（分页）
  _fetchMoreData(){
    if (!this._hasData() || this.state.isLodingTail) {
      return; //没有更多数据或数据正在加载中，则不处理
    }
    this._fetchData(cachedResults.nextpage); //获取下一页的数据
  },

  //下载刷新，加载数据
  _onRefresh(){
    if (!this._hasData() || this.state.isRefreshing) {
      return; //没有更多数据或正在下拉刷新中，则不处理
    }
    this._fetchData(0); //获取新的数据
  },

  //底部加载更多区域逻辑
  _renderFooter(){
    if (this.state.isLodingTail) { //正在加载数据时显示空
      return (<View style={styles.loadingMore}/>)
    }

    if (this._hasData() || cachedResults.total === 0) {  //还有数据，或从未加载过数据，显示加载图标
      return (
        <ActivityIndicator style={styles.loadingMore}/>
      )
    }

    return (
      <View style={styles.loadingMore}><Text style={styles.loadingText}>没有更多了</Text></View>
    )
  },

  render() {
    return (
      <View style={styles.container} >
        <Header title="列表页面" bgColor="#ee735c"/>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this._renderRow}
          onEndReached={this._fetchMoreData}
          onEndReachedThreshold={20} //滑动到距离底部触发onEndReached事件的临界值
          showsVerticalScrollIndicator={false}  //不显示垂直滚动条
          renderFooter={this._renderFooter} //页面底部区域内容（加载更多）
          refreshControl={  //下载刷新
            <RefreshControl
              refreshing={this.state.isRefreshing}
              onRefresh={this._onRefresh}
              tintColor="#ff6600"
              title="拼命加载中..."
            />
          }
          enableEmptySections={true} //为了去掉warn加的代码
          automaticallyAdjustContentInsets={false}  //去掉ListView的头部出现莫名其妙的空白
        />
      </View>
    )
  }
})

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF'
  },

  /*列表项样式*/
  item: {
    width: width,
    marginBottom: 10,
    backgroundColor: '#fff'
  },
  thumb: {
    width: width,
    height: width * 0.5,
    resizeMode: 'cover'
  },
  play: {
    position: 'absolute',
    right: 14,
    bottom: 14,
    width: 46,
    height: 46,
    paddingLeft: 18,
    paddingTop: 9,
    backgroundColor: 'transparent',
    borderColor: '#fff',
    borderWidth: 1,
    borderRadius: 23,
    color: '#ed7b66'
  },
  up: {
    color: '#ed7b66',
    fontSize: 22
  },
  down: {
    color: '#333',
    fontSize: 22
  },
  comment: {
    color: '#333',
    fontSize: 22
  },
  title: {
    padding: 10,
    fontSize: 18,
    color: '#333'
  },
  itemFooter: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    backgroundColor: '#eee'
  },
  handleBox: {
    flexDirection: 'row',
    justifyContent: 'center',
    width: width / 2 - 0.5,
    backgroundColor: '#fff',
    padding: 5
  },
  handleText: {
    paddingLeft: 12,
    fontSize: 18,
    color: '#333'
  },


  /*加载更多*/
  loadingMore: {
    marginVertical: 20
  },
  loadingText: {
    color: '#777',
    textAlign: 'center'
  }

});

module.exports = List

